package com.hank.jms.queue;

import javax.jms.*;


class ConsumerMesasge extends Thread {
    String consumerName;
    ConnectionFactory connectionFactory;

    public ConsumerMesasge(ConnectionFactory connectionFactory, String consumerName) {
        this.consumerName = consumerName;
        this.connectionFactory = connectionFactory;
    }

    public void run() {
        startConsumer(connectionFactory, "Consumer " + consumerName );
    }

    public void startConsumer(ConnectionFactory connectionFactory, String conSumerName) {
        Connection connection = null;
        try {
            //通过工厂获取一个连接
            connection = connectionFactory.createConnection();
            connection.start();

            //通过连接创建一个会话,并默认关闭事务,自动确认消息
            Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            //通过会话构建一个目的地
            Destination destination = session.createQueue("static-network-queue");
            //再通过session创建一个消息发送者，并设定发送目的地对象

            //异步消费
            MessageConsumer consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage msg = (TextMessage) message;
                    try {
                        System.out.println(conSumerName + "Receiver Message >>" + msg.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}